﻿using AutoMapper;
using MediatR;
using Traceability.Doamin;
using Traceability.ErrorCode;
using Traceability.Infratruvture.Interfares;
using Traceability.Write.Api.Application.Command;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;

namespace Traceability.Write.Api.Application.CommandHander
{
    public class AddImagerHander : IRequestHandler<AddImagerCommand, ApiResult<int>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRequsitory<Imager> imagerRequsitory;
        private readonly IBaseRequsitory<Commodity> commodityRequsitory;

        public AddImagerHander(IMapper mapper, IBaseRequsitory<Imager> imagerRequsitory, IBaseRequsitory<Commodity> commodityRequsitory)
        {
            this.mapper = mapper;
            this.imagerRequsitory = imagerRequsitory;
            this.commodityRequsitory = commodityRequsitory;
        }

        /// <summary>
        /// 添加图片表处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddImagerCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.添加成功;
            result.Msg = ApiEnum.添加成功.ToString();

            if (string.IsNullOrEmpty(request.ImagerName))
            {
                return result;
            }

            // 按逗号拆分 ImagerName，并过滤掉空字符串，同时进行去重
            var imagerNames = request.ImagerName.Trim().Split(',')
                .Where(x => !string.IsNullOrEmpty(x))
                .Select(x => x.Trim())
                .Distinct()
                .ToList();

            foreach (var name in imagerNames)
            {
                var newRequest = new AddImagerCommand
                {
                    ImagerName = name,
                    ModuleId = request.ModuleId,
                    CommodityId = request.CommodityId
                };

                var entity = mapper.Map<Imager>(newRequest);

                await imagerRequsitory.AddAsync(entity);
            }

            return await Task.FromResult(result);
        }
    }
}